package com.bigShen.pattern.observer.event;

import com.bigShen.pattern.observer.mouse.MouseEventType;
import com.bigShen.pattern.observer.mouse.MouseServiceCallBack;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : lei.shen
 * @date : 2018/10/7
 */
public class EventListener {

    private static Map<MouseEventType, Event> events = new HashMap<MouseEventType, Event>();

    static {
        try {
            MouseServiceCallBack callBack = new MouseServiceCallBack();

            Method clickCallBackMethod = callBack.getClass().getMethod("click", new Class[]{Event.class});
            Method dbClickCallBackMethod = callBack.getClass().getMethod("dbClick", new Class[]{Event.class});
            Method upCallBackMethod = callBack.getClass().getMethod("up", new Class[]{Event.class});
            Method downCallBackMethod = callBack.getClass().getMethod("down", new Class[]{Event.class});

            Event clickEvent = new Event(callBack, clickCallBackMethod, MouseEventType.ON_CLICK.toString());
            Event dbClickEvent = new Event(callBack, dbClickCallBackMethod, MouseEventType.ON_DBCLICK.toString());
            Event upEvent = new Event(callBack, upCallBackMethod, MouseEventType.ON_UP.toString());
            Event downEvent = new Event(callBack, downCallBackMethod, MouseEventType.ON_DOWN.toString());

            events.put(MouseEventType.ON_CLICK, clickEvent);
            events.put(MouseEventType.ON_DBCLICK, dbClickEvent);
            events.put(MouseEventType.ON_UP, upEvent);
            events.put(MouseEventType.ON_DOWN, downEvent);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public void addListener(MouseEventType type, Object listener, Method callback) {
        Event event = new Event(listener, callback, type.toString());
        events.put(type, event);
    }


    public void trigger(MouseEventType type) {
        if (!events.containsKey(type)) {
            System.out.println("没有匹配类型的监听!");
            return;
        } else {
            // 执行监听
            Event event = events.get(type);
            try {
                event.setPublisher(this);
                event.setTime(System.currentTimeMillis());
                event.getCallback().invoke(event.getListener(), event);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

}
